﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Public;
using BUS;

namespace QuanLyKhoHangVatTu
{
    public partial class ChuyenKho : DevExpress.XtraEditors.XtraForm
    {
        ChuyenKho_BUS ck_bus = new ChuyenKho_BUS();
        ChuyenKho_PB ck_pb = new ChuyenKho_PB();
        Flag_PB flag_pb = new Flag_PB();
        int SLTon = 0;
        string khoxuat = "";
        string khonhap = "";
        string mahang = "";
        public ChuyenKho()
        {
            InitializeComponent();
        }

        private void ChuyenKho_Load(object sender, EventArgs e)
        {
            cboNguoiVanChuyen.Properties.DataSource = ck_bus.LayDSNV();
            cboNguoiVanChuyen.Properties.DisplayMember = "Mã NV";
            cboNguoiVanChuyen.Properties.ValueMember = "Tên NV";

            colMaHang.DataSource = ck_bus.LayDSVatTu();
            colMaHang.DisplayMember = "MAVATTU";
            colMaHang.ValueMember = "MAVATTU";

            colXuatTaiKho.DataSource = ck_bus.LayDSKho();
            colXuatTaiKho.DisplayMember = "TENKHO";
            colXuatTaiKho.ValueMember = "MAKHO";



            colNhapTaiKho.DataSource = ck_bus.LayDSKho();
            colNhapTaiKho.DisplayMember = "TENKHO";
            colNhapTaiKho.ValueMember = "MAKHO";

            DataTable dt = ck_bus.LayDSCTChuyenKho();
            gridControl1.DataSource = dt;

            if (Flag_PB.ThemSua == 1)
            {
                txtMa.ResetText();
                cboNguoiVanChuyen.ResetText();
                txtNguoiVanChuyen.ResetText();
                dtNgayChungTu.ResetText();
                dtNgayHachToan.ResetText();
                try
                {
                    txtMa.Text = ck_bus.NextID_CK();
                }
                catch
                {
                    txtMa.Text = "CK0001";
                }

                EnableEditing(false);
            }
            if (Flag_PB.ThemSua == 2)
            {
                txtMa.Text = ChuyenKho_PB.MaChuyenKho;
                cboNguoiVanChuyen.SelectedText = ChuyenKho_PB.NguoiVanChuyen;
                txtNguoiVanChuyen.Text = ChuyenKho_PB.TenNguoiVanChuyen;
                txtDienGiai.Text = ChuyenKho_PB.DienGiai;
                dtNgayHachToan.EditValue = ChuyenKho_PB.NgayHachToan;
                dtNgayChungTu.EditValue = ChuyenKho_PB.NgayChungTu;

                gridControl1.DataSource = ck_bus.TimMaPhieuChuyenKho(txtMa.Text);

                EnableEditing(false);
                menuXoa.Enabled = true;

                this.gridView1.NewItemRowText = "Sửa chi tiết nhập kho";
                this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                DataRowView row1 = gridView1.GetFocusedRow() as DataRowView;
                if (row1 == null) return;

                SLTon = Int32.Parse(row1["SOLUONG"].ToString());
                mahang = row1["MAHANG"].ToString();
                khoxuat = row1["XUATTAIKHO"].ToString();
                khonhap = row1["NHAPTAIKHO"].ToString();
            }
        }

        private void cboNguoiVanChuyen_EditValueChanged(object sender, EventArgs e)
        {
            txtNguoiVanChuyen.Text = cboNguoiVanChuyen.EditValue.ToString();
        }

        #region "Enable Controls"
        private void EnableEditing(bool editing)
        {
            menuThem.Enabled = editing;
            menuSua.Enabled = editing;
            menuXoa.Enabled = editing;
            menuLuu.Enabled = !editing;
            menuHoan.Enabled = !editing;
            menuDong.Enabled = !editing;
        }
        private void EnableTextBox(bool editing)
        {
            txtMa.Enabled = editing;
            cboNguoiVanChuyen.Enabled = editing;
            txtNguoiVanChuyen.Enabled = editing;
            txtDienGiai.Enabled = editing;
            dtNgayChungTu.Enabled = editing;
            dtNgayHachToan.Enabled = editing;
            gridControl1.Enabled = editing;
        }
        #endregion

        #region"Kiểm tra rỗng"
        private bool CheckNull()
        {
            if (txtMa.Text == "" || cboNguoiVanChuyen.Text == "" || txtNguoiVanChuyen.Text == ""|| dtNgayHachToan.Text == "" || dtNgayChungTu.Text == "")
            {
                return false;
            }
            return true;
        }
        #endregion

        #region "Lấy giá trị textbox"
        private ChuyenKho_PB GetValues()
        {
            ChuyenKho_PB.MaChuyenKho = txtMa.Text;
            ChuyenKho_PB.NguoiVanChuyen = cboNguoiVanChuyen.Text;
            ChuyenKho_PB.DienGiai = txtDienGiai.Text;
            ChuyenKho_PB.NgayHachToan = Convert.ToDateTime(dtNgayHachToan.EditValue);
            ChuyenKho_PB.NgayChungTu = Convert.ToDateTime(dtNgayChungTu.EditValue);
            return ck_pb;
        }
        #endregion

        private void menuLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.DataRowCount > 0)
            {
                for (int i = gridView1.RowCount - 1; i >= 0; i--)
                {
                    ChuyenKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                    ChuyenKho_PB.XuatTaiKho = gridView1.GetRowCellValue(i, "XUATTAIKHO").ToString();
                    ChuyenKho_PB.NhapTaiKho = gridView1.GetRowCellValue(i, "NHAPTAIKHO").ToString();
                    ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                    ChuyenKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                    ChuyenKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());

                    if (ChuyenKho_PB.MaHang == "" || ChuyenKho_PB.XuatTaiKho == "" || ChuyenKho_PB.NhapTaiKho == "" || ChuyenKho_PB.SoLuong == "" || ChuyenKho_PB.ThanhTien.ToString() == "" || ChuyenKho_PB.DonGia.ToString() == "")
                    {
                        MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết chuyển kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (ChuyenKho_PB.XuatTaiKho == ChuyenKho_PB.NhapTaiKho)
                    {
                        MessageBox.Show("Kho nhập và kho xuất không được trùng nhau", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (ck_bus.CheckExists(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho))
                    {
                        int sl = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho);
                        if (sl < Int32.Parse(ChuyenKho_PB.SoLuong))
                        {
                            MessageBox.Show("Không thể chuyển vật tư, hàng hóa <" + ChuyenKho_PB.MaHang + "> quá số lượng trong tồn kho.\nSố lượng trong tồn kho là: " + sl, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Không thể chuyển vật tư, hàng hóa <" + ChuyenKho_PB.MaHang + "> quá số lượng trong tồn kho.\nSố lượng trong tồn kho là: 0", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                }
                if (CheckNull())
                {
                    if (Flag_PB.ThemSua == 1)
                    {
                        GetValues();
                        ck_bus.ThemChuyenKho(ck_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            try
                            {
                                ChuyenKho_PB.ID = ck_bus.NextID_CTC();
                            }
                            catch
                            {
                                ChuyenKho_PB.ID = "CTC0001";
                            }
                            ChuyenKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            ChuyenKho_PB.XuatTaiKho = gridView1.GetRowCellValue(i, "XUATTAIKHO").ToString();
                            ChuyenKho_PB.NhapTaiKho = gridView1.GetRowCellValue(i, "NHAPTAIKHO").ToString();
                            ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            ChuyenKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            ChuyenKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                            ck_bus.ThemCTChuyenKho(ck_pb);

                            //nếu mã hàng ở kho chuyển tồn tại thì update số lượng, ngược lại thêm
                            int sl1 = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho);
                            sl1 -= Int32.Parse(ChuyenKho_PB.SoLuong);
                            ChuyenKho_PB.SoLuong = sl1.ToString();
                            ck_bus.SuaTonKhoXuat(ck_pb);
                            if (ck_bus.CheckExists(ChuyenKho_PB.MaHang, ChuyenKho_PB.NhapTaiKho))
                            {
                                int sl = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.NhapTaiKho);
                                ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                sl += Int32.Parse(ChuyenKho_PB.SoLuong);
                                ChuyenKho_PB.SoLuong = sl.ToString();
                                ck_bus.SuaTonKhoNhap(ck_pb);
                            }
                            else
                            {
                                ChuyenKho_PB.MaTK = ck_bus.NextID_TK();
                                ck_bus.ThemTonKho(ck_pb);

                            }
                            

                            //DataTable dt = ck_bus.TimMaTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho);
                            //if (dt != null)
                            //{
                            //    foreach (DataRow r in dt.Rows)
                            //    {
                            //        string matk = r["MATK"].ToString();
                            //    }
                            //}
                        }
                    }
                    if (Flag_PB.ThemSua == 2)
                    {
                        GetValues();
                        ck_bus.SuaChuyenKho(ck_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            ChuyenKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            ChuyenKho_PB.XuatTaiKho = gridView1.GetRowCellValue(i, "XUATTAIKHO").ToString();
                            ChuyenKho_PB.NhapTaiKho = gridView1.GetRowCellValue(i, "NHAPTAIKHO").ToString();
                            ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            ChuyenKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            ChuyenKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                            ChuyenKho_PB.ID = gridView1.GetRowCellValue(i, "ID").ToString();
                            ck_bus.SuaCTChuyenKho(ck_pb);

                            if (SLTon > Int32.Parse(ChuyenKho_PB.SoLuong))
                            {
                                //update nhap tai kho
                                int sl1 = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.NhapTaiKho);
                                sl1 -=(SLTon- Int32.Parse(ChuyenKho_PB.SoLuong));
                                ChuyenKho_PB.SoLuong = sl1.ToString();
                                ck_bus.SuaTonKhoNhap(ck_pb);
                                //update xuat tai kho
                                ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                SLTon -= Int32.Parse(ChuyenKho_PB.SoLuong);
                                int sl = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho);
                                sl += SLTon;
                                ChuyenKho_PB.SoLuong = sl.ToString();
                                ck_bus.SuaTonKhoXuat(ck_pb);
                                
                            }
                            else
                            {
                                //update nhap tai kho
                                int sl1 = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.NhapTaiKho);
                                sl1 += (Int32.Parse(ChuyenKho_PB.SoLuong)-SLTon);
                                ChuyenKho_PB.SoLuong = sl1.ToString();
                                ck_bus.SuaTonKhoNhap(ck_pb);
                                //update xuat tai kho
                                ChuyenKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                int a = Int32.Parse(ChuyenKho_PB.SoLuong);
                                a -= SLTon;
                                int sl = ck_bus.LaySLTonKho(ChuyenKho_PB.MaHang, ChuyenKho_PB.XuatTaiKho);
                                sl -= a;
                                ChuyenKho_PB.SoLuong = sl.ToString();
                                ck_bus.SuaTonKhoXuat(ck_pb);
                            }
                        }
                    }
                    menuThem.Enabled = true;
                    menuSua.Enabled = false;
                    menuXoa.Enabled = false;
                    menuLuu.Enabled = false;
                    menuHoan.Enabled = false;
                    menuDong.Enabled = true;
                    EnableTextBox(false);
                }
                else
                {
                    MessageBox.Show("Vui lòng điền đầy đủ thông tin Phiếu chuyển kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết chuyển kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void menuThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Flag_PB.ThemSua = 1;
            EnableTextBox(true);
            txtMa.ResetText();
            txtNguoiVanChuyen.ResetText();
            dtNgayChungTu.ResetText();
            dtNgayHachToan.ResetText();
            txtMa.Text = ck_bus.NextID_CK();

            EnableEditing(false);
            gridControl1.DataSource = ck_bus.LayDSCTChuyenKho();

            this.gridView1.NewItemRowText = "Click để thêm 1 dòng mới";
            this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.True;
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void menuXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            menuHoan.Enabled = false;

            if (MessageBox.Show("Bạn có thực sự muốn xóa (những) dòng đã chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                for (int i = gridView1.GetSelectedRows().Length - 1; i >= 0; i--)
                {
                    ChuyenKho_PB.ID = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[i], "ID").ToString();
                    ck_bus.XoaCTChuyenKho(ck_pb);
                }
                gridControl1.DataSource = ck_bus.TimID(ck_pb);
            }
        }

        private void menuDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = DialogResult.OK;
            this.Close();
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            DataRowView row = gridView1.GetFocusedRow() as DataRowView;
            if (row == null) return;

            row["SOLUONG"] = 1;
            row["DONGIA"] = 0;
        }

        private void colMaHang_EditValueChanged(object sender, EventArgs e)
        {
            var lkpMaHang = sender as LookUpEdit;
            if (lkpMaHang == null) return;

            DataRow row = gridView1.GetFocusedDataRow();
            if (row == null) return;

            // tim ten hang rồi gán cho row["tenhang"]
            DataTable dtVattu = lkpMaHang.Properties.DataSource as DataTable;
            if (dtVattu == null) return;

            dtVattu.PrimaryKey = new DataColumn[] { dtVattu.Columns["MAVATTU"] };
            DataRow vattu = dtVattu.Rows.Find(lkpMaHang.EditValue);
            if (vattu == null) return;

            row["TENVATTU"] = vattu["TENVATTU"];
            row["DIENGIAI"] = vattu["DIENGIAI"];
            row["DONGIA"] = vattu["DONGIAMUA"];


        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow chiTiet = gridView1.GetFocusedDataRow();
            if (chiTiet == null) return;

            chiTiet["THANHTIEN"] = Convert.ToDecimal(chiTiet["SOLUONG"]) * Convert.ToDecimal(chiTiet["DONGIA"]);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void gridControl2_Click(object sender, EventArgs e)
        {

        }
    }
}